import Vue from "vue";
import VueRouter from "vue-router";
import store from "../store/index.js";
import Home from "../views/Home.vue";

Vue.use(VueRouter);
const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
    meta: {
      level: 0, //页面级别
    },
  },
  {
    path: "/about",
    // name: "About",
    component: () => import("../views/About.vue"),
    meta: {
      level: 0, //页面级别
    },
    children: [
      {
        name: "Setting",
        path: "/about/setting",
        component: () => import("../views/modules/Setting.vue"),
      },
    ],
  },
  {
    path: "/404",
    name: "404",
    component: () => import("../views/404.vue"),
    meta: {
      level: 0,
    },
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/Login.vue"),
    // meta: {
    //   level: 1,
    // },
  },
  {
    path: "*",
    component: () => import("../views/404.vue"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
  isBack: false,
});
/**
 * 改变路由切换动画
 * @param {*} to
 * @param {*} from
 */
function changeRouterTransittion(to, from) {
  let isBack = router.isBack;
  console.log(
    "根组件监听 ",
    `From [${from.fullPath}] To [${to.fullPath}] =${isBack ? "后退" : "前进"}`
  );
  if (isBack) {
    // this.transitionName = "slide-right";
    store.commit("setTransitionName", "child-view-slide-right");
  } else {
    // this.transitionName = "slide-left";
    store.commit("setTransitionName", "child-view-slide-left");
  }
  router.isBack = false;
}
/**
 * 检测是否已登录
 *
 */
function hasAuthLogin(to, from) {
  if (to.path == "/login" || from.path == "/login") {
    return;
  }
  console.log(from);
  if (!localStorage.getItem("token") || !store.state.hasLogined) {
    Vue.prototype.$dialog
      .alert({
        title: "提示",
        message: "未登录，请先登录",
      })
      .then(() => {
        store.commit("setFullPage", true);
        router.push("/login?from=" + from.path);
      });
  }
}
let current = "/";
router.beforeEach((to, from, next) => {
  changeRouterTransittion(to, from);
  hasAuthLogin(to, from); //拦截登录
  if (to.meta.level == 0) {
    store.commit("setFullPage", false);
  }
  next();
  current = to.fullPath;
});

VueRouter.prototype.goBack = function() {
  this.isBack = true; //判断是否是返回操作
  if (current == "/") {
    return;
  }
  window.history.go(-1);
};
// 二级页面跳转
VueRouter.prototype.goTo = function(path) {
  this.isBack = false; //判断是否是返回操作
  store.commit("setFullPage", true);
  router.replace(path);
};

export default router;
